package ruc.InfluxDB.read;

import okhttp3.Request;
import ruc.Consts.constant;
import ruc.utils.IOUtils;
import ruc.InfluxDB.InfluxDB_Common;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;

public class InfluxDB_DiffResSet {
    private static final int CLIENT = 15;
    private int bound;
    private String tbName;
    private String queryURL = "";

    public InfluxDB_DiffResSet(String IP, String port, String dbName, String tbName, int bound) {
        String baseUrl = String.format("http://%s:%s", IP, port);
        this.queryURL = baseUrl + "/query?db=" + dbName;
        this.tbName = tbName;
        this.bound = bound;
    }

    public long convertAndSend(String eSql) {
        String tmp = queryURL + "&q=" + eSql;

        Request request = new Request.Builder()
                .url(tmp)
                .build();

        return InfluxDB_Common.sendRequest(request);
    }

    public long query(int limit, int offset) {
        String sqlFormat = "select * from %s limit %d offset %d";
        String eSql = String.format(sqlFormat, tbName, limit, offset);

        return convertAndSend(eSql);
    }

    public void DiffResSetRead(int record[]) throws InterruptedException {
        Random random = new Random();
        for(int i = 0; i < record.length; i++) {
            CountDownLatch CDL = new CountDownLatch(CLIENT);
            AtomicLong AL = new AtomicLong(0);
            for(int j = 0; j < CLIENT; j++) {
                int finalI = i;
                new Thread(()->{
                    AL.addAndGet(query(random.nextInt(bound), record[finalI]));
                    CDL.countDown();
                }).start();
            }

            CDL.await();
            System.out.printf("[TSBench-D] >>>>> [InfluxDB_DiffResSet] record Line : %d, average response time : %d >>>>> \n", record[i], AL.longValue() / 15);
            IOUtils.WriteData(constant.GetWriteFilePath("InfluxDB", "DiffResSet"),
                    new String[]{String.valueOf(System.nanoTime()), String.valueOf(record[i]), String.valueOf(AL.longValue() / CLIENT)});
        }
    }

    public static void main(String[] args) throws InterruptedException {
        InfluxDB_DiffResSet db = new InfluxDB_DiffResSet(constant.IP, constant.InfluxDB_Port, constant.dbName, constant.Concurrent_tbName, constant.bound);
        db.DiffResSetRead(constant.RecordNum);
    }
}
